$(function () {
    //暂存单表格
    var temporary_datagrid = $("#guaranteeBill_datagrid");
    //暂存单信息弹出框
    var temporary_dialog = $("#temporary_dialog");
    //编辑弹出框
    var edit_dialog = $("#edit_dialog");
    //已选商品信息列表
    var product_datagrid = $("#productInfo_datagrid");
    //所有商品列表
    var allproduct_dialog = $("#allproduct_dialog"); //弹窗
    var allProductInfo_datagrid = $("#allProductInfo_datagrid");//表格
    //投保人弹出框
    var client_dialog = $("#client_dialog");

    //查看保单 已选明细
    var showproductInfo_datagrid = $("#showproductInfo_datagrid");
    var show_dialog = $("#show_dialog");
    //表单
    var client_form = $("#client_form");

    //公共的车辆info id
    var carInfoId = null;
    //公共的车辆保单号
    var billNumber = null;
    /** =====================================暂存单表格===================================== */
    temporary_datagrid.datagrid({
        //设置只查询状态为暂存单状态的保单
        url: "/guaranteeBill/queryTemporary?state=1",
        fitColumns: true,
        fit: true,
        striped: true,
        pagination: true,
        pageSize: 10,
        pageNumber: 1,
        singleSelect: true,
        toolbar: "#temporary_toolbar",
        columns: [
            [
                {field: 'id', checkbox: true},
                {field: 'number', title: '保险单号', width: 80},
                {
                    field: 'policyClient.id', hidden: true, formatter: function (value, row) {
                        if (row.policyClient) {

                            return row.policyClient.id
                        }
                    }
                },
                {
                    field: 'policyClient', title: '投保人', width: 80, formatter: function (value, row) {
                        if (row.policyClient) {
                            return row.policyClient.name;
                        }
                    }
                },
                {field: 'vdate', title: '申请日期', width: 80},
                {field: 'limitYear', title: '保险时长', width: 80},
                {
                    field: 'opEmployee', title: '业务员', width: 80, formatter: function (value, row) {
                        if (value) {
                            return value.username;
                        }
                    }
                },
                {field: 'totalPrice', title: '投保总金额', width: 80},
                {field: 'state', title: '状态', width: 80, formatter: function (value, row) {
                        if (value) {
                            return "<font color='red'>暂存单状态</font>";
                        }
                    }
                }
            ]]
    });
    /** ==================================================================================== */
    /** =====================================自定义函数====================================== */
    var objMethod = {
        //多条件查询
        query: function () {
            //获得当前输入文本框的值
            var clientName = $("#clientName").textbox('getValue')
            var sn = $("#sn").textbox('getValue')
            //加载的时候把参数传递过去
            temporary_datagrid.datagrid('load', {
                clientName: clientName,
                sn: sn
            });
        },
        //编辑方法
        edit: function () {
            var row = temporary_datagrid.datagrid("getSelected");
            if (!row) {
                $.messager.alert("温馨提示", '至少选择一条数据', 'warning')
                return;
            }
            carInfoId = row.carId;
            billNumber = row.number;
            //传递车辆信息
            $.get('/car/selectCarByBillId', {id: row.car.id}, function (data){
                    //维护属性carSizeDetail.id
                    data["loadSize.id"] = data.loadSize.id;
                    $("#carinfo_form").form('load',data);
            });
            //传递产品信息
            $.get("/product/selectProductList",{number:row.number},function (data) {
                if (data) {
                    //产品机构id 回显
                    $("#agencyInfo_combobox").combobox('setValue',data[0].company.id);
                    //产品明细数据加载
                    product_datagrid.datagrid('loadData',data);
                }
                //保险年限 row.limitYear
                $("#limitYear_input").textbox('setValue',row.limitYear);
                //总价显示
                $("#totalAmount1").html(row.totalPrice);
            });
            edit_dialog.dialog('open');
            edit_dialog.dialog('center');
        },
        //编辑完成后提交表单
        save: function () {
            $("#carinfo_form").form('submit', {
                url: '/guaranteeBill/editGuaranteeBill',
                onSubmit: function (params) {
                    //维护已选择数据参数
                    var rows = product_datagrid.datagrid('getRows');
                    var ids = $.map(rows, function (value) {
                       return value.id;
                    });
                    var totalAmount =  $("#totalAmount1").html();

                    params["carInfoId"] = carInfoId;
                    params["snNumber"] = billNumber;
                    params["totalAmount"] = totalAmount;
                    params["ids"] = ids;
                    params["limitYear"] = $("#limitYear_input").textbox('getValue');
                },
                success: function (data) {
                    data = $.parseJSON(data)
                    if (data.success) {
                        $.messager.alert('温馨提示', '编辑成功', 'info', function () {
                            edit_dialog.dialog('close');
                            temporary_datagrid.datagrid('reload')
                        });
                    } else {
                        $.messager.alert("温馨提示", data.msg, "warning")
                    }
                }
            })
        },
        //关闭方法
        close: function () {
            temporary_dialog.dialog('close')
        },
        //取消方法
        cancel: function () {
            edit_dialog.dialog('close')
        },
        //刷新方法
        refresh: function () {
            //鍒锋柊鏁版嵁琛ㄦ牸
            temporary_datagrid.datagrid('reload')

        },
        //提审的方法
        audit: function () {
            var row = temporary_datagrid.datagrid('getSelected');
            //如果没有选择车辆信息的一条记录
            if (row == null) {
                $.messager.alert('温馨提示', '至少选择一条记录', 'error');
                return;
            }
           $.messager.alert('温馨提示','确定要提审吗?','info',function () {
               $.post("/receiptBill/changeStateUnaudited", {id:row.id}, function (data) {
                   if (data.success) {
                       $.messager.alert('温馨提示', '提审成功!!!', 'info', function () {
                           temporary_datagrid.datagrid('load');
                       });
                   } else {
                       $.messager.alert('温馨提示', '提审失败!!!', 'error');
                   }
               })
           })
        },
        //编辑时选择详细的商品时候选择的内容
        chose:function(){
           var proRows= allProductInfo_datagrid.datagrid('getSelections');
            if (proRows.length <= 0) {
                $.messager.alert("温馨提示", '至少选择一条数据', 'warning');
                return;
            }
            product_datagrid.datagrid('loadData',proRows);
            allproduct_dialog.dialog('close');
            changeTotalAmount(  $("#limitYear_input").textbox('getValue'))
        }
    };
    $('a[data-cmd]').click(function () {
        objMethod[$(this).data('cmd')]();
    });
    /** ======================================编辑弹出框======================================== */
    //编辑弹出框初始化
    edit_dialog.dialog({
        modal: true,
        closed: true,
        title: '编辑保单信息',
        width: 700,
        height: 470,
        buttons: '#edit_buttons',
        top: 200,
        onClose:function () {
            //清楚表单数据
            $("#carinfo_form").form("clear");
        }
    });


    /** ====================================编辑弹出框内容==================================== */
    //已选择商品表格
    product_datagrid.datagrid({
        url: '/product/selectProductList',
        fitColumns: true,
        toolbar:'#edit_productInfo_buttons',
        rownumbers: true,
        columns: [[
            {field: 'id', hidden: true},
            {field: 'name', title: '产品名称', width: 100},
            {field: 'annualFee', title: '保险年费', width: 100},
            {field: 'limitYear', title: '年限', width: 100, align: 'right'}
        ]]
    });
    //删除已选商品明细按钮
    $("#edit_productInfo_delete").click(function () {
        var rows =  product_datagrid.datagrid('getSelections');
        //如果没有选择车辆信息的一条记录
        if (rows.length == 0) {
            $.messager.alert('温馨提示', '至少选择一条记录', 'error');
            return;
        }
        for (var i = rows.length - 1; i >= 0; i--) {

            product_datagrid.datagrid('deleteRow', i);
        }
        changeTotalAmount(  $("#limitYear_input").textbox('getValue'))
    });
    //根据输入年份求总额
    $("#limitYear_input").textbox({
        width: 60,
        onChange: function (newValue, oldValue) {
            var rows = $("#productInfo_datagrid").datagrid('getRows');
            var totalAmount = 0;
            for (var i = rows.length - 1; i >= 0; i--) {
                totalAmount = totalAmount + rows[i].annualFee;
            }
            totalAmount = parseFloat(totalAmount * newValue);
            $("#totalAmount1").html(totalAmount);
        }
    });
    //弹出所有商品按钮
    $("#add_linkbutton").linkbutton({
        iconCls: 'icon-add',
        onClick: function () {
            //判断是否选择机构
            var agencyId = $("#agencyInfo_combobox").val();
            // console.log(agencyId);
            if (!agencyId) {
                $.messager.alert("温馨提示", "至少选择一个承保机构", "info")
                return
            }
            //加载当前机构的产品信息
            allProductInfo_datagrid.datagrid('load',{agencyId:agencyId});
            allproduct_dialog.dialog('open');
            allproduct_dialog.dialog('center')
        }
    });

    //弹出框
    allproduct_dialog.dialog({
        modal: true,
        closed: true,
        title: '选择保险产品',
        width: 700,
        height: 450,
        onclose: function () {
            product_datagrid.datagrid('loadData ', [])
        }
    });
    //所有商品表格
    allProductInfo_datagrid.datagrid({
        url:'/product/query',
        fit:true,
        fitColumns:true,
        rownumbers:true,
        toolbar:'#chose_buttons',
        pagination: true,
        columns:[[
            {field:'id',checkbox:true},
            {field:'sn', title:'保险编号', width:80},
            {field:'name', title:'产品名称', width:80},
            {field:'company', title:'所属机构', width:80,formatter:function (value, row, index) {
                    return value.name;
                }},
            {field:'year', title:'保障年限', width:80},
            {field:'money', title:'保额', width:40},
            {field:'annualFee', title:'年费', width:40},
            {field:'saleState', title:'状态', width:40, formatter:function (value, row, index) {
                    return value ?  "<font color='green'>在售</font>" : "<font color='red'>停售</font>";}},
            {field:'deductState', title:'不计免赔', width:80, formatter:function (value, row, index) {
                    return value ?  "<font color='green'>是</font>" : "<font color='red'>否</font>";}}
        ]]
    });

    /** ====================================保单查看弹出框=================================== */
    $("#showBill").click(function () {
        //编辑方法
        var row = temporary_datagrid.datagrid("getSelected");
        if (!row) {
            $.messager.alert("温馨提示", '至少选择一条数据', 'warning')
            return;
        }
        //传递车辆信息,将car的id传递过去查询当前车辆的信息
        $.get('/car/selectCarByBillId', {id: row.car.id}, function (data){
            //维护属性carSizeDetail.id
            //数据字典的时候使用data["carSizeDetail.id"] = data.carSizeDetail.id;
            $("#showCarinfo_form").form('load',data);
        });
        //传递产品信息,将当前行的保单编码传递到后台通过保单编号查询当前产品信息,当前行是guaranteeBill的对象
        $.get("/product/selectProductList",{number:row.number},function (data) {
            if (data) {
                //产品机构id 回显
                $("#showAgencyInfo_combobox").combobox('setValue',data[0].company.id);
                //产品明细数据加载
                showproductInfo_datagrid.datagrid('loadData',data);
            }
            //保险年限 从暂存单当中获取row.limitYear
            $("#showlimitYear_input").textbox('setValue',row.limitYear);
            //总价显示
            $("#showtotalAmount1").html(row.totalPrice);
        });
        show_dialog.dialog('open');
        show_dialog.dialog('center');

    });
    //初始化弹窗
    $("#show_dialog").dialog({
        modal: true,
        closed: true,
        title: '查看保单信息',
        width: 700,
        height: 470,
        buttons: '#showInfo_buttons',
        top: 200
    });
    //保单详情查看
    showproductInfo_datagrid.datagrid({
        url: '/product/selectProductList',
        fitColumns: true,
        rownumbers: true,
        singleSelect: true,
        columns: [[
            {field: 'id', hidden: true},
            {field: 'name', title: '产品名称', width: 100},
            {field: 'annualFee', title: '保险年费', width: 100},
            {field: 'year', title: '年限', width: 100, align: 'right'}
        ]]
    });
    //点击关闭事件
    $("#showInfo_cancel").click(function () {
        $("#show_dialog").dialog("close");
    });

    /** ======================================投保人弹框=================================== */
    client_dialog.dialog({
        width: 350,
        height: 370,
        closed: true,
        modal: true,
        top: 30,
        buttons: "#form_btns",
        title:'查看投保人明细',
        onClose: function () {
            client_form.form("clear");
        }
    });
    //表格弹出点击事件
    $("#showClient").click(function () {
        var row = temporary_datagrid.datagrid('getSelected');
        if (!row) {
            $.messager.alert("温馨提示", '至少选择一条数据', 'warning')
            return;
        }
          $.get("/guaranteeBill/selectClientByBillId", {id: row.policyClient.id},function (data) {
              //加入职业 薪资 客户来源的属性
              data["resource.name"] = data.resource.name;
              data["job.name"] = data.job.name;
              data["income.name"] = data.income.name;
              client_form.form('load',data)
          },'json');
        client_dialog.dialog('open')
    });

    /** ==================================================================================== */

});
 function changeTotalAmount(year) {
    var rows = $("#productInfo_datagrid").datagrid('getRows');
    var totalAmount = 0;
    for (var i = rows.length - 1; i >= 0; i--) {
        totalAmount = totalAmount + rows[i].annualFee;
    }
    totalAmount = parseFloat(totalAmount * year);
    $("#totalAmount1").html(totalAmount);
}